package br.com.commerj.dao;

import java.sql.SQLException;
import java.sql.Types;

import br.com.commerj.model.Endereco;

public class EnderecoDAO extends DAO{
	
	
	public String salvar(Endereco endereco){
		String msg = "";
		p = null;
		c = null;
		try{
			String sql = "INSERT INTO endereco VALUES(?,?,?,?,?,?,?)";
			p = getConnection().prepareStatement(sql);
			p.setNull(1, Types.NULL);
			p.setString(2, endereco.getLogradouro());
			p.setString(3, endereco.getNumero());
			p.setString(4, endereco.getComplemento());
			p.setString(5, endereco.getBairro());
			p.setString(6, endereco.getCidade());
			p.setString(7, endereco.getEstado());
			p.execute();
			c.commit();
			msg = "SALVAR";
		}catch (SQLException e) {
			msg = "Erro no método Salvar, classe EnderecoDAO"+e.getMessage();
		}finally{
			try{
			if(p != null)
				p.close();
			if(c != null)
				c.close();
			}catch (SQLException e) {
				System.out.println("Erro ao fechar Conexão e Statement"+e.getMessage());
			}
		}
		return msg;
	}
	
	public Integer lastId() throws SQLException{
		Integer lastId = 0;
		p = null;
		c = null;
		r = null;
		try{
			String sql = "SELECT MAX(codEndereco) as codEndereco from endereco"; 
			p = getConnection().prepareStatement(sql);
			r = p.executeQuery();
			if(r.next())
				lastId = r.getInt(1);
			p.execute();
			c.commit();
			
		}catch(SQLException e){
			System.out.println("Erro método lastId classe EnderecoDAO"+e.getMessage());
		}finally{
			try{
				if(p != null)
					p.close();
				if(c != null)
					c.close();
				if(r != null)
					r.close();
				}catch (SQLException e) {
					System.out.println("Erro ao fechar Conexão e Statement"+e.getMessage());
				}
		}	
		return lastId;
	}
	

}
